#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
每天监控招聘数据入了多少联系方式表
'''

import json
import sys
sys.path.append('/mnt/moonbrook/Moonbrook')
from aes import contact_aes, name_aes
import subprocess
import os
import re
import psutil
import time
import requests
from copy import deepcopy
from datetime import datetime, timedelta
from pybloom_live import ScalableBloomFilter
from apscheduler.schedulers.blocking import BlockingScheduler

from base import ExportAndTjBase
from utils import Utils
from models import MongoQueryConfig, RobotConfig
from robot import DingtalkRobot

reload(sys)
sys.setdefaultencoding('utf-8')


class ExportAndTj(ExportAndTjBase):
    week_min, week_max = Utils.get_date_range(ndays=1)

    def __init__(self, *args, **kwargs):
        super(ExportAndTj, self).__init__(*args, **kwargs)
        self.desc_file_name = '/mnt5/dsf/recruiting/desc_recruiting_nameId_and_contact_{}'.format(
            self.week_min.strftime("%Y-%m-%d"))

    def is_in_contact(self, nameId, contact):
        '''
        通过nameId找到该企业所有联系方式数据,然后返回 指定的contact那条数据
        @param nameId:
        @param contact:
        @return:
        '''
        dic_ls = list(self.contact_col.find({'nameId': nameId},["contact"]))
        for encrypt_dic in dic_ls:
            # decrypt_dic = Utils.decrypt_one_record(encrypt_dic, need_decrypt=True)
            # print(encrypt_dic)
            decrypt_contact = contact_aes.decrypt(encrypt_dic['contact'])
            if decrypt_contact == contact:
                return True
        return False

    def run(self):
        # save_result_dic可以放入类变量中，避免传参调用导致逻辑混乱
        save_result_dic = {
            'into_contact_table_count': 0,  # 入联系方式表数量
        }
        if os.path.exists(self.desc_file_name):
            with open(self.desc_file_name,'r') as f:
            # with open('/mnt5/dsf/recruiting/desc_recruiting_nameId_and_contact','r') as f:
                for line in f:
                    line = line.strip()
                    nameId, mobile = line.split('\t',1)
                    flag = self.is_in_contact(nameId,mobile)
                    # print(nameId,mobile,flag)
                    if flag:
                        save_result_dic['into_contact_table_count'] += 1
        # 机器人相关
        url = RobotConfig.dsf_s2_web_hook_url
        title = RobotConfig.dsf_s2_title
        robot = DingtalkRobot(self.write_robot_f)
        mk_text = self.make_mk_text(save_result_dic)
        robot.main(url, title=title, mk_text=mk_text)
    def make_mk_text(self, result_dic):
        '''通过数据 拼接出mk_text'''
        result_dic = Utils.serializable_bloom(result_dic)
        mk_text = ''

        mk_text += '''  
                    **==========**  
                    **昨日招聘数据入联系方式表条数：{}**  
                    **==========**  
                    '''.format(result_dic['into_contact_table_count'])

        return mk_text


def run(abs_file_name):
    export_and_tj = ExportAndTj(abs_file_name)
    export_and_tj.main()


def scheduler_run(abs_file_name):
    scheduler = BlockingScheduler()
    scheduler.add_job(func=run, trigger='cron',
                      args=(abs_file_name,),
                      day="*",
                      hour='23', minute='10', id='dd_run_2')
    scheduler.start()


if __name__ == '__main__':
    file_name = '招聘定时统计昨天入contact数据'
    # py文件名+file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name, current_py_path=__file__, name='dsf')

    # run(abs_file_name)
    scheduler_run(abs_file_name)
